﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.Script.Serialization;
using System.Text;
using System.Collections;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net;
using System.IO;

namespace Nova_Common
{
    public static class HttpHelper
    {
        #region HttpGet
        /// <summary>
        /// http请求服务器
        /// </summary>
        /// <param name="URL">服务器地址</param>
        /// <param name="sReInfo">返回信息</param>
        /// <returns></returns>
        public static int GetHTTP(string URL, out string sReInfo)
        {
            sReInfo = "";
            try
            {
                WebRequest myRequest = WebRequest.Create(URL);
                WebResponse myResponse = myRequest.GetResponse();
                Stream myResponseStream = myResponse.GetResponseStream();
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("UTF-8"));
                sReInfo = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponse.Close();

                return 1;
            }
            catch (Exception exp)
            {
                sReInfo = exp.Source + exp.Message;
                return 0;
            }
        }

        /// <summary>
        /// http请求服务器
        /// </summary>
        /// <param name="URL">服务器地址</param>
        /// <param name="sReInfo">返回信息</param>
        /// <returns></returns>
        public static int GetHTTP(string URL, string sSave_Path, string sSave_Name, out string sReInfo)
        {
            sReInfo = "";
            int iRes;
            string sPath = sSave_Path + sSave_Name;
            try
            {
                WebRequest myRequest = WebRequest.Create(URL);
                WebResponse myResponse = myRequest.GetResponse();

                if (!myResponse.ContentType.ToLower().StartsWith("text/"))
                {
                    iRes = SaveBinaryFile(myResponse, sPath);
                    return iRes;
                }
                else
                {
                    Stream myResponseStream = myResponse.GetResponseStream();
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("UTF-8"));
                    sReInfo = myStreamReader.ReadToEnd();
                    myStreamReader.Close();
                    myResponse.Close();

                    return 1;
                }
            }
            catch (Exception exp)
            {
                sReInfo = exp.Source + exp.Message;
                return 0;
            }
        }

        private static int SaveBinaryFile(WebResponse response, string savePath)
        {
            int iRes = 0;
            byte[] buffer = new byte[1024];
            Stream outStream = null;
            Stream inStream = null;
            try
            {
                if (File.Exists(savePath)) File.Delete(savePath);
                outStream = System.IO.File.Create(savePath);
                inStream = response.GetResponseStream();
                int l;
                do
                {
                    l = inStream.Read(buffer, 0, buffer.Length);
                    if (l > 0) outStream.Write(buffer, 0, l);
                } while (l > 0);
                iRes = 1;
            }
            finally
            {
                if (outStream != null) outStream.Close();
                if (inStream != null) inStream.Close();
            }
            return iRes;
        }
        #endregion

        #region HttpPost
        /// <summary>
        /// POST 服务器
        /// </summary>
        /// <param name="buffer">发送信息</param>
        /// <param name="URL">请求地址</param>
        /// <param name="sReInfo">返回信息</param>
        /// <returns></returns>
        public static int HttpPoster(string sValue, string URL, out string sReInfo)
        {
            sReInfo = "";

            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sValue);

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(URL);

            req.Method = "POST";
            req.Accept = "text/html, application/xhtml+xml, */*";
            req.ContentType = "application/json";  
            //req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = buffer.Length;
            try
            {
                Stream reqst = req.GetRequestStream();
                reqst.Write(buffer, 0, buffer.Length);
                reqst.Flush();
                reqst.Close();
            }
            catch
            {
                sReInfo = "请求异常";
                return 0;
            }

            try
            {
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                Stream resst = res.GetResponseStream();
                StreamReader sr = new StreamReader(resst, System.Text.Encoding.GetEncoding("UTF-8"), true);
                sReInfo = sr.ReadToEnd();
                sr.Close();
                resst.Close();

                return 1;
            }
            catch
            {
                sReInfo = "回应异常";
                return 0;
            }
        }

        /// <summary>
        /// POST 服务器
        /// </summary>
        /// <param name="buffer">发送信息</param>
        /// <param name="URL">请求地址</param>
        /// <param name="sReInfo">返回信息</param>
        /// <returns></returns>
        public static int HttpPoster(Encoding ed, string sValue, string URL, out string sReInfo)
        {
            sReInfo = "";

            HttpWebRequest req;
            try
            {
                req = (HttpWebRequest)WebRequest.Create(URL);
                byte[] buffer = ed.GetBytes(sValue);

                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = buffer.Length;
                Stream reqst = req.GetRequestStream();
                reqst.Write(buffer, 0, buffer.Length);
                reqst.Flush();
                reqst.Close();
            }
            catch
            {
                sReInfo = "请求异常";
                return 0;
            }

            try
            {
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();
                Stream resst = res.GetResponseStream();
                StreamReader sr = new StreamReader(resst, System.Text.Encoding.GetEncoding("UTF-8"), true);
                sReInfo = sr.ReadToEnd();
                sr.Close();
                resst.Close();

                return 1;
            }
            catch
            {
                sReInfo = "回应异常";
                return 0;
            }
        }
        #endregion

        /// <summary>
        /// 将json数据转成DataTable
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static DataTable JsonToDataTable(string json)
        {
            DataTable dtRet = new DataTable();

            try
            {
                json = json.Trim();
                if (json[0] != '[')
                    json = "[" + json;
                if (json[json.Length - 1] != ']')
                    json = json + "]";

                JavaScriptSerializer jss = new JavaScriptSerializer();
                ArrayList arrList = jss.Deserialize<ArrayList>(json);

                if (arrList.Count > 0)
                {
                    foreach (Dictionary<string, object> arrRow in arrList)
                    {
                        if (dtRet.Columns.Count == 0)
                        {
                            foreach (string key in arrRow.Keys)
                            {
                                if (key.Equals("tagid_list"))
                                {
                                    continue;
                                }
                                dtRet.Columns.Add(key, arrRow[key].GetType());
                            }
                        }
                        DataRow dr = dtRet.NewRow();
                        foreach (string key in arrRow.Keys)
                        {
                            if (key.Equals("privilege") || key.Equals("tagid_list"))
                            {
                                continue;
                            }
                            dr[key] = System.Web.HttpUtility.UrlDecode(arrRow[key]._ToString(), System.Text.Encoding.UTF8);
                        }
                        dtRet.Rows.Add(dr);
                    }
                }
                return dtRet;
            }
            catch (Exception exp)
            {
                return dtRet;
            }
        }
    }
}
